//
//  DateTimeHelper.m
//  RegBars
//
//  Created by Huu Nhat on 7/27/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "DateTimeHelper.h"
#import "RegBarsAppDelegate_iPhone.h"

@implementation DateTimeHelper

- (id)init{
    if ((self = [super init])) {
        // Initialization code here.
    }
    
    return self;
}

- (void)dealloc{
//    [aa release];
//    [arrDayWeek release];
    [ngayOfthang release];
    [super dealloc];
}

- (NSInteger)namNhuanWith:(NSInteger)nam
{
    if (!(nam % 400))
        return 1;
    if (!(nam % 4) && (nam % 100)) 
        return 1;
    return 0;
}

//  Cong thuc tinh weekday:
//                     _ Y - 1 _        _ Y - 1 _        _ Y - 1 _                  //
//   F(Y) = Y - 1 ++  |  -----  |  --  |  -----  |  ++  |  -----  |  ++  C
//                    |_   4   _|      |_  100  _|      |_  400  _|

//   NOTE: Y: Current year
//         C: so ngay tu ngay dau nam den ngay can tinh
//   F(Y) mod 7  =  1 : thu hai
//               =  2 : thu ba
//               =  ...
//               =  0 : chu nhat



- (NSString*) calculateDate:(NSDate*) date{
    arrDayWeek = [[NSMutableArray alloc] initWithObjects:Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, nil];
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd/MM/yyyy - HH:mm:aa"];
    NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];
//    dateLabel.text = stringDate;
    NSArray *dateArray = [stringDate componentsSeparatedByString:@"/"];
    day = [[dateArray objectAtIndex:0] intValue];
    month = [[dateArray objectAtIndex:1] intValue];
    NSArray *tempArray = [[dateArray objectAtIndex:2] componentsSeparatedByString:@" "];
    year = [[tempArray objectAtIndex:0] intValue];
    aa = [[NSString alloc] init];
    NSArray *timeArray = [[tempArray lastObject] componentsSeparatedByString:@":"];
    hour = [[timeArray objectAtIndex:0] intValue];
    minute = [[timeArray objectAtIndex:1] intValue];
    aa = [timeArray objectAtIndex:2];
    
    
    NSInteger y = year;
    NSInteger d = day;
    if ([self namNhuanWith:y]==1) {
        [ngayOfthang replaceObjectAtIndex:2 withObject:@"29"];
    }
    for (int i = 1; i < month; ++i)
        d += [[ngayOfthang objectAtIndex:i] intValue];
    
    
    int res = (y - 1) + (y - 1) / 4 - (y - 1) / 100 + (y - 1) / 400 + d;
    NSLog(@"%@",arrDayWeek);
    NSLog(@"thu : %@",[arrDayWeek objectAtIndex:(res % 7)]);
    return [arrDayWeek objectAtIndex:(res % 7)];
    if ([aa isEqualToString:@"AM"]) {
        if (hour < 6 || hour == 12) {
            int thu = (res % 7)-1;
            if (res %7 == 0) {
                thu = 6;
            }
        }
    }
    NSLog(@"%@", [ngayOfthang objectAtIndex:1]);
    [ngayOfthang replaceObjectAtIndex:2 withObject:@"28"];
}

@end
